/*
 * Another rip-off alert - this is ALL from GMail Checker Plus!
 */

var canvasContext;
var rotation = 1;
var factor = 1;
var animTimer;
var loopTimer;
var animDelay = 10;

function initGraphics() {
    canvasContext = canvas.getContext('2d');
}

function startAnimate() {
  stopAnimateLoop();
    
  if(1) {
    animTimer = setInterval("doAnimate()", animDelay);
    setTimeout("stopAnimate()", 800);
  } else {
    stopAnimate();
  }
}

function stopAnimate() {
  if(animTimer != null)
    clearTimeout(animTimer);       

  chrome.browserAction.setIcon({path:gfx.src});
    
  rotation = 1;
  factor = 1;
}

function stopAnimateLoop() {
  if(loopTimer != null)
    clearTimeout(loopTimer);
    
  stopAnimate();
}

function doAnimate() {
  canvasContext.save();
  canvasContext.clearRect(0, 0, canvas.width, canvas.height);
  canvasContext.translate(
   Math.ceil(canvas.width/2),
   Math.ceil(canvas.height/2));
  canvasContext.rotate(rotation*2*Math.PI);
  canvasContext.drawImage(gfx,
   -Math.ceil(canvas.width/2),
   -Math.ceil(canvas.height/2));
  canvasContext.restore();
  
  rotation += 0.01 * factor;
  
  if(rotation <= 0.9 && factor < 0)
    factor = 1;
  else if(rotation >= 1.1 && factor > 0)
    factor = -1;        
    
  chrome.browserAction.setIcon({imageData:canvasContext.getImageData(0, 0,
   canvas.width,canvas.height)});
}